<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\madmin\service;

use app\madmin\model\Merchant;
use app\madmin\model\MerchantCash;
use app\madmin\model\MerchantWithdraw as admin;
use app\madmin\model\RechargeRecord;
use app\madmin\model\User;
use app\utils\TrimData;
use think\Exception;

class MerchantWithdrawService
{

    /**
     * 查询列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function findAll(array $data, int $page = 1, int $size = 10)
    {

        if (isset($data['merchant_name'])) {
            global $user;
            $admin = admin::withoutGlobalScope(['mallId'])->scope('merchantSearch', $data)
                ->where("mw.mall_id",$user->mall_id)
                ->field('mw.id,withdraw,mw.service_charge,mw.is_online,mw.type,mw.card,serial_num,mw.status,mw.remark,mw.pay_no,mw.pay_time,mw.create_time,mw.update_time,m.id merchant_id,m.name merchant_name');
        } else {
            $admin = admin::with(['merchant'])
                ->field('id,merchant_id,withdraw,service_charge,is_online,type,card,serial_num,status,remark,pay_no,pay_time,create_time,update_time');
            $admin = TrimData::searchDataTrim($admin, $data, ['begin_date', 'end_date']);
            $admin = $admin->where($data);
        }

        $list = $admin->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 读取一条数据
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(int $id)
    {
        $model = admin::find($id);
        return [HTTP_SUCCESS, $model];
    }


    /**
     * 更新数据
     * @param int $id
     * @param array $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws Exception
     */
    public function update(int $id, array $data)
    {
        $update_time = $data['update_time'];
        unset($data['update_time']);
        $model = admin::where(['update_time' => $update_time])->lock(true)->find($id);

        if (!$model)
            throw new Exception("没有该记录", HTTP_NOTACCEPT);

        if ($model->getData("status") == $data['status'])
            throw new Exception("该操作无法执行", HTTP_NOTACCEPT);

        $merchant = Merchant::find($model->merchant_id);


        $user = User::where(['id' => $merchant->user_id])->with('wx')->find();
        if (!$user)
            throw new Exception("用户不是商户", HTTP_NOTACCEPT);

        if ($model->getData("status") == 0 && $data['status'] == 2) {
            $update = MerchantCash::where(['merchant_id' => $model->merchant_id])
                ->dec("withdraw", (double)$model->withdraw)
                ->inc("recharge", (double)$model->withdraw)
                ->update();
            if (empty($update))
                throw new \PDOException("取消失败");
            $data['pay_no'] = null;
        } elseif ($model->getData("status") == 0 && $model->is_online == 1 && $data['status'] == 1) {
            switch ($user->wx->type) {
                case 2:
                    $baseIn = "wechat";
                    $method = "wx";
                    break;
                case 1:
                    $baseIn = "wechata";
                    $method = "wx";
                    break;
            }
            $paymentService = new PaymentService();
            $arr = $paymentService->merchantTransfers(
                $baseIn,
                $method,
                $user->wx->openid,
                (double)bcsub((string)$model->withdraw, (string)$model->service_charge)
            );
            if ($arr['result_code'] !== "SUCCESS") {
                throw new Exception($arr['err_code_des'], HTTP_NOTACCEPT);
            }
            $data['pay_no'] = $arr["payment_no"];
            $data['pay_time'] = $arr["payment_time"];
        } else {
            $data['pay_no'] = null;
        }

        $admin = admin::where('update_time', $update_time)
            ->where('id', $id)
            ->save($data);

        if (!$admin) {
            throw new Exception("更新失败", HTTP_NOTACCEPT);
        }

//        RechargeRecord::update(
//            [
//                'status' => $data['status'],
//                'pay_no' => $data['pay_no']
//            ],
//            ['trade' => $model->serial_num]
//        );

        return [HTTP_CREATED, $admin];
    }

    /**
     * @param $id
     * @return int
     */
    public function delete($id)
    {
        admin::destroy($id);
        return HTTP_NOCONTEND;
    }

}
